﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.DomainServices.Client;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AppLab;
using AppLab.Models;
using AppLab.Web;
using AppLab.Web.Services;
using Wicresoft.AppFlow.Flows;

namespace AppLab.Views
{
    public partial class Task : Page
    {
        private IList<OperationBase> possiblyPendingOperations = new List<OperationBase>();
        private FlowContext flow = new FlowContext();
        private TaskSubmitData task = new TaskSubmitData();
        /// <summary>
        /// 控制每页DateGrid的行数
        /// </summary>
        private const int pageSize = 6;
        //页面加载时，固定保存用户名(WebContext.Current.User.Name,获取具有延迟性)
        private string userName = WebContext.Current.User.Name;

        public Task()
        {
            InitializeComponent();
            PageScrollViewer.SetIsMouseWheelScrollingEnabled(true);
            this.Title = ApplicationStrings.TaskPageTitle;
            this.DataContext = task;
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            BindGrid(0, string.Empty);
            this.BindAutoCompleteOfMobileType();
        }

        #region 分页处理，每次加载一页

        private void BindGrid(int pageIndex, string type)
        {
            busyIndicatorLoad.IsBusy = true;
            InvokeOperation<int> iCount = flow.GetTaskCount(type);
            iCount.Completed += new EventHandler(iCount_Completed);

            var query = flow.GetTaskDataGridQuery(pageSize, pageIndex, type);
            LoadOperation<TaskSubmitData> loadOp = flow.Load(query);
            loadOp.Completed += new EventHandler(loadOp_Completed);
        }

        void loadOp_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            dataGridTableList.ItemsSource = loadOp.Entities;
            dataGridTableList.SelectedIndex = 0;

            if (loadOp.TotalEntityCount <= 0)
            {
                //该页记录审核完，跳到第一页
                if (dpTaskInfo.PageIndex > 0)
                {
                    dpTaskInfo.PageIndex = 0;
                    this.BindGrid(0, this.autoCompleteBoxMbBrand.Text.Trim());
                }
                else
                {
                    this.detailInfo.IsHitTestVisible = false;
                    this.TipsForAdaptation.Text = ApplicationStrings.TipsForNoNewTaskededAdaptation;
                }
            }
            else
            {
                this.detailInfo.IsHitTestVisible = true;
            }

            busyIndicatorLoad.IsBusy = false;
        }

        void iCount_Completed(object sender, EventArgs e)
        {
            InvokeOperation invokeOp = (InvokeOperation)sender;
            if (dpTaskInfo.PageIndex <= 0)
            {
                dpTaskInfo.BindSource((int)(invokeOp.Value), pageSize);
                dpTaskInfo.PageIndexChanged -= new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
                dpTaskInfo.PageIndexChanged += new EventHandler<EventArgs>(dpReviewInfo_PageIndexChanged);
            }
        }

        void dpReviewInfo_PageIndexChanged(object sender, EventArgs e)
        {
            BindGrid(dpTaskInfo.PageIndex, autoCompleteBoxMbBrand.Text.Trim());
        }
        #endregion

        // Executes when the user tries to leave this page.
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            foreach (OperationBase operation in this.possiblyPendingOperations)
            {
                if (!operation.IsComplete)
                {
                    if (operation.CanCancel)
                    {
                        operation.Cancel();
                    }
                    else
                    {
                        e.Cancel = true;
                    }
                }
            }
        }

        private void buttonSubmit_Click(object sender, RoutedEventArgs e)
        {
            if (!Verification()) return;

            userName = WebContext.Current.User.Name;

            TaskSubmitData tsd = new TaskSubmitData();
            TaskSubmitData selItem = (TaskSubmitData)dataGridTableList.SelectedItem;
            tsd.FlowGuid = selItem.FlowGuid;
            tsd.TestTypeID = selItem.TestTypeID;
            tsd.TestResultID = (bool)rdoAccept.IsChecked ? FlowState.TestSucceeded : ((bool)rdoReject.IsChecked ? FlowState.TestFailed : FlowState.PendingPublish);
            tsd.TestReportName = this.tbTestReport.selectedFile.Name;
            tsd.TestReport = this.tbTestReport.taskSubmitData.TestReport;

            //Email需要的额外数据
            tsd.SubmitByAlias = selItem.SubmitByAlias;
            tsd.AssignedToAlias = selItem.AssignedToAlias;
            tsd.MobileBrand = selItem.MobileBrand;
            tsd.MobileType = selItem.MobileType;
            tsd.MobileVersion = selItem.MobileVersion;
            tsd.SubmitBy = selItem.SubmitBy;
            tsd.SubmitTime = selItem.SubmitTime;
            tsd.ReviewBy = selItem.ReviewBy;
            tsd.ReviewTime = selItem.ReviewTime;
            tsd.AssignedTo = selItem.AssignedTo;

            task.CurrentOperation = this.flow.Task(
                   tsd.FlowGuid,
                   tsd,
                   this.TaskOperation_Completed, null);

            this.possiblyPendingOperations.Add(task.CurrentOperation);
        }

        private void TaskOperation_Completed(InvokeOperation<Guid> operation)
        {
            if (!operation.IsCanceled)
            {
                if (operation.HasError)
                {
                    ErrorWindow.CreateNew(operation.Error);
                    operation.MarkErrorAsHandled();
                }
                else if (operation.Value != Guid.Empty)
                {
                    MessageBox.Show(PopupDialogStrings.CompletedTask, this.Title, MessageBoxButton.OK);
                    Clear();
                    this.tbTestReport.selectedFile = null;
                    BindGrid(dpTaskInfo.PageIndex, this.autoCompleteBoxMbBrand.Text.Trim());
                }
                else
                {
                    ErrorWindow.CreateNew(ErrorResources.ErrorWindowGenericError);
                }
            }
        }

        private bool Verification()
        {
            if (!WebContext.Current.User.IsAuthenticated)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.MustBeLoggedInString;
                return false;
            }
            else if (dataGridTableList.SelectedItem == null)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.SelectedAcceptanceClientOnTask;
                return false;
            }
            else if (string.IsNullOrEmpty(this.tbTestReport.Text))
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.UploadInspectionReportOnTask;
                return false;
            }
            else if (this.tbTestReport.taskSubmitData.TestReport == null)
            {
                this.TipsForWrongInfo.Text = PopupDialogStrings.UploadWrongInspectionReportOnTask;
                return false;
            }
            else
            {
                return true;
            }
        }

        private void Clear()
        {
            this.rdoAccept.IsChecked = true;
            this.tbTestReport.Text = string.Empty;
            this.TipsForWrongInfo.Text = string.Empty;
        }

        private void dataGridTableList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Clear();
            if (dataGridTableList.SelectedItem != null)
            {
                this.TipsForAdaptation.Text = (dataGridTableList.SelectedItem as TaskSubmitData).MoblieBrandAndType + ApplicationStrings.TipsForAdaptationStr;
            }
        }

        private void tbTestReport_KeyDown(object sender, KeyEventArgs e)
        {
            e.Handled = true;
            if ((Keyboard.Modifiers & ModifierKeys.Control) == 0)
            {
                e.Handled = true;
            }
        }

        private void tbTestReport_TextChanged(object sender, TextChangedEventArgs e)
        {
            this.TipsForWrongInfo.Text = string.Empty;
            (sender as TextBox).IsReadOnly = true;
        }

        #region 搜索

        private ComboBox comb = new ComboBox();
        private void BindAutoCompleteOfMobileType()
        {
            var query = flow.GetMobileTypesQuery(-1);

            LoadOperation<MobileType> load = flow.Load(query);
            load.Completed += new EventHandler(load_Completed);
        }

        void load_Completed(object sender, EventArgs e)
        {
            LoadOperation loadOp = (LoadOperation)sender;
            comb.ItemsSource = loadOp.Entities;
            BindAutoCompleteBox(comb);
        }

        private void BindAutoCompleteBox(ComboBox comb)
        {
            List<String> listStr = new List<string>();
            for (int i = 0; i < comb.Items.Count; i++)
            {
                MobileType e = comb.Items[i] as MobileType;
                listStr.Add(e.TypeName);
            }
            autoCompleteBoxMbBrand.ItemsSource = listStr;
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            this.dpTaskInfo.PageIndex = 0;
            BindGrid(this.dpTaskInfo.PageIndex, autoCompleteBoxMbBrand.Text.Trim());
        }
        #endregion


    }
}
